layui.define(['element','config','jquery','form'],function(exports){
	var $element = layui.element,
		$ = layui.jquery,
		$config = layui.config(),
	    $form = layui.form;

	var layId,
	Tab = function(){
		this.tabConfig = {
			closed : true,
			openTabNum : 10,
			tabFilter : "bodyTab"
		}
	};

	//参数设置
	Tab.prototype.set = function(option) {
		var _this = this;
		$.extend(true, _this.tabConfig, option);
		return _this;
	};

	//通过title获取lay-id
	Tab.prototype.getLayId = function(title){
		$(".layui-tab-title.top_tab li").each(function(){
			if($(this).find("cite").text() == title){
				layId = $(this).attr("lay-id");
			}
		});
		return layId;
	};
	//通过title判断tab是否存在
	Tab.prototype.hasTab = function(title){
		var tabIndex = -1;
		$(".layui-tab-title.top_tab li").each(function(){
			if($(this).find("cite").text() == title){
				tabIndex = 1;
			}
		});
		return tabIndex;
	};

	//通过title查找tab
	Tab.prototype.getTab = function(title){
		$(".layui-tab-title.top_tab li").each(function(){
			if($(this).find("cite").text() == title){
				return this;
			}
		});
		return null;
	};

	//右侧内容tab操作
	Tab.prototype.tabAdd = function(_this){
		var that = this;
		var tabFilter = that.tabConfig.tabFilter;

		//如果已经打开tab
		if(that.hasTab(_this.find("cite").text()) ==1){
			$element.tabChange(tabFilter, that.getLayId(_this.find("cite").text()));
		}else{
			var url = _this.attr("data-url");
			if(!url){
				return;
			}

			/*var title = '<i class="iconfont">' + _this.find(".iconfont").attr("data-icon") + '</i>';*/
			var title = '';
			title += '<cite>'+_this.find("cite").text()+'</cite>';
			title += '<i class="layui-icon layui-unselect layui-tab-close">&#x1006;</i>';

			var lay_id = new Date().getTime();
			$element.tabAdd(tabFilter, {
				title : title,
				content :"<iframe src='" + $config.config.baseUrl + url + "'></frame>",
				id : lay_id
			});

			$form.render();
			$element.tabChange(tabFilter, lay_id);
		}
	};

	//删除tab
	$("body").on("click",".top_tab li i.layui-tab-close",function(){
		$element.tabDelete("bodyTab",$(this).parent("li").attr("lay-id")).init();
	});

	var bodyTab = new Tab();
	exports("bodyTab",function(option){
		return bodyTab.set(option);
	});
});